package middleware

import (
	"blogcenter/internal/utils"
	"context"
	"net/http"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type contextKey string

const (
	UserIdKey contextKey = "userId"
)

// 直接返回rest.Middleware类型
func NewAuthMiddleware(secret string) rest.Middleware {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			// 1. 获取token
			authHeader := r.Header.Get("Authorization")
			if authHeader == "" {
				httpx.WriteJson(w, http.StatusUnauthorized, map[string]interface{}{
					"code":    401,
					"message": "未提供认证token",
				})
				return
			}

			// 2. 提取Bearer token
			token := strings.TrimPrefix(authHeader, "Bearer ")
			if token == authHeader {
				httpx.WriteJson(w, http.StatusUnauthorized, map[string]interface{}{
					"code":    401,
					"message": "token格式错误，需要Bearer token",
				})
				return
			}

			// 3. 解析token
			claims, err := utils.ParseToken(token, secret)
			if err != nil {
				logx.Errorf("解析token失败: %v", err)
				httpx.WriteJson(w, http.StatusUnauthorized, map[string]interface{}{
					"code":    401,
					"message": "无效的token: " + err.Error(),
				})
				return
			}

			// 4. 将用户信息存入上下文
			ctx := context.WithValue(r.Context(), UserIdKey, claims.UserId)
			next(w, r.WithContext(ctx))
		}
	}
}
